package com.qiuzhiyi.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.li.utils.ImageUtil;
import com.li.utils.InputFilterUtil;
import com.li.utils.TransformUtil;
import com.li.utils.UriUtil;
import com.li.widget.TopNavigationBar;
import com.qiuzhiyi.R;
import com.qiuzhiyi.adapter.FaTieImgAdapter;
import com.qiuzhiyi.base.QZYBaseActivity;
import com.qiuzhiyi.item.FaTieImgItem;
import com.qiuzhiyi.net.ObservableHelper;
import com.qiuzhiyi.net.RetrofitHelper;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class TiWenActivity extends QZYBaseActivity {

    private static final int REQUEST_CODE_CHOOSE = 0;
    private static final int REQUEST_CODE_CHANGE = 1;
    private static final int MAX_NUM = 1;
    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.txt_name)
    TextView mTxtName;
    @BindView(R.id.et_des)
    EditText mEtDes;
    @BindView(R.id.recycler)
    RecyclerView mRecycler;
    @BindView(R.id.layout_des)
    LinearLayout mLayoutDes;
    private FaTieImgAdapter mAdapter;
    private List<FaTieImgItem> mImgItemList;
    private int mCurrentPos;
    private String mTitle;
    private String mPicUrl;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_ti_wen;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        File file = new File(Environment.getExternalStorageDirectory(), "Pictures");
        if (!file.exists()) {
            if (!file.mkdir()) {
                showToast("请打开存储权限");
            }
        }

        mTitle = getIntent().getStringExtra("title");
        mTxtName.setText(mTitle);
        mEtDes.setFilters(new InputFilter[]{new InputFilterUtil.NoEmojiFilter()});
        mImgItemList = new ArrayList<>();
        mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
        mAdapter = new FaTieImgAdapter(R.layout.item_fatie_img);
        mRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                GridLayoutManager manager = ((GridLayoutManager) parent.getLayoutManager());
                int spanCount = manager.getSpanCount();
                outRect.bottom = TransformUtil.dp2px(mContext, 5);
                if ((parent.getChildAdapterPosition(view) + 1) % spanCount == 0) {
                    outRect.right = TransformUtil.dp2px(mContext, 0);
                } else {
                    outRect.right = TransformUtil.dp2px(mContext, 5);
                }
            }
        });
        mAdapter.bindToRecyclerView(mRecycler);
        mImgItemList.add(new FaTieImgItem());
        mAdapter.setNewData(mImgItemList);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                FaTieImgItem tagImageView = mImgItemList.get(position);
                if (tagImageView.getUri() == null) {
                    if (mImgItemList.size() > MAX_NUM) {
                        showToast("配图只能为一张");
                        return;
                    }
                    int num = MAX_NUM - (mImgItemList.size() - 1);
                    Matisse.from(mActivity)
                            .choose(MimeType.allOf())
                            .countable(false)
                            .capture(true)
                            .captureStrategy(
                                    new CaptureStrategy(true, "com.qiuzhiyi.fileprovider"))
                            .maxSelectable(num)
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .forResult(REQUEST_CODE_CHOOSE);
                } else {
                    mCurrentPos = position;
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                            .setTitle("提示")
                            .setItems(new CharSequence[]{"删除", "重新选择"}, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            mAdapter.remove(mCurrentPos);
                                            mPicUrl = null;
                                            break;
                                        case 1:
                                            Matisse.from(mActivity)
                                                    .choose(MimeType.allOf())
                                                    .countable(false)
                                                    .capture(true)
                                                    .captureStrategy(
                                                            new CaptureStrategy(true, "com.qiuzhiyi.fileprovider"))
                                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                                    .thumbnailScale(0.85f)
                                                    .imageEngine(new GlideEngine())
                                                    .forResult(REQUEST_CODE_CHANGE);
                                            break;
                                    }
                                }
                            });
                    builder.create().show();

                }
            }
        });
    }

    @Override
    public void onFunctionTxtListener(View view) {
        if (TextUtils.isEmpty(mPicUrl) || TextUtils.isEmpty(mEtDes.getText().toString())) {
            showToast("请完善描述和配图");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("是否要提交此次问题？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确地", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        quiz(mUid, mItem.getHumanAccount(), mTxtName.getText().toString(), mEtDes.getText().toString(), mPicUrl);
                    }
                });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CHOOSE:
                    List<Uri> uris = Matisse.obtainResult(data);
                    List<FaTieImgItem> items = new ArrayList<>();
                    for (Uri uri : uris) {
                        FaTieImgItem imgItem = new FaTieImgItem();
                        imgItem.setUri(uri);
                        items.add(imgItem);
                    }
                    mAdapter.addData(0, items);

                    break;
                case REQUEST_CODE_CHANGE:
                    FaTieImgItem imgItem = new FaTieImgItem();
                    imgItem.setUri(Matisse.obtainResult(data).get(0));
                    mAdapter.setData(mCurrentPos, imgItem);

                    break;
            }
            String filePath = UriUtil.getRealPathFromUri(mContext, Matisse.obtainResult(data).get(0));
            dealFile(filePath);
        }
    }

    /**
     * 异步处理
     *
     * @param filePath 文件路径
     */
    private void dealFile(final String filePath) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(filePath, options);
                int normalWidth = options.outWidth;
                int width = TransformUtil.dp2px(mContext, 50);

                int sample = 1;
                if (normalWidth > width) {
                    sample = normalWidth / width;
                }
                if (sample <= 0) {
                    sample = 1;
                }
                options.inSampleSize = sample;
                options.inJustDecodeBounds = false;
                Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
                File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Pictures/head.jpg");
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(file));
                String base = ImageUtil.bitmapToBase64(bitmap);
                e.onNext(base);
                e.onComplete();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoadingDialog("正在处理图片");
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(String s) {
                        uploadPic(s);

                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 上传图片
     *
     * @param s base64
     */
    private void uploadPic(String s) {
        Map<String, String> map = new HashMap<>();
        map.put("humanPicUrl", s);
        ObservableHelper.createObservable(RetrofitHelper.createService().uploadQuizPic(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在上传图片");
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject object = new JSONObject(s);
                            object = object.getJSONObject("paramMap");
                            mPicUrl = object.getString("humanPicUrl");
                        } catch (JSONException e) {
                            e.printStackTrace();
                            mPicUrl = null;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });
    }

    private void quiz(String humanId, String humanAccount, String title, String content, String humanPicUrl) {
        Map<String, String> map = new HashMap<>();
        map.put("humanId", humanId);
        map.put("humanAccount", humanAccount);
        map.put("title", title);
        map.put("content", content);
        map.put("humanPicUrl", humanPicUrl);
        ObservableHelper.createObservable(RetrofitHelper.createService().quiz(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在提交");
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject object = new JSONObject(s);
                            if (object.getString("code").equals("200")) {
                                showToast("提交成功");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        showToast("提交失败，请重新提交");
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });
    }
}
